Repository navigation
fix(datalayer): schedule count on monotonic clock - #1418
Draft
ithinkihaveacat wants to merge 1 commit into
Draft
ithinkihaveacat wants to merge 1 commit into
ithinkihaveacat wants to merge 1 commit into
Conversation
Anchor MainActivity's periodic /count sender loop to monotonic SystemClock.elapsedRealtime() on a fixed 5-second grid instead of resetting lastTriggerTime = Instant.now() after delay() returns. Previously, overwriting lastTriggerTime after delay() permanently shifted subsequent deadlines later by every main-looper wakeup overshoot (O(N) phase drift), and reading Instant.now() coupled the sleep duration to mutable wall-clock adjustments (stalling across backward NTP/NITZ or manual clock steps). Advance deadlines from the prior scheduled slot via nextCountTriggerRealtimeMs(), skipping already-elapsed intervals if a sendCount() call or main-thread stall exceeds 5 seconds so recovery does not emit a back-to-back catch-up burst. Document that periodic DataClient writes are for sample demonstration traffic only, and add JUnit 4 unit tests covering wakeup overshoots, sub-interval IPC latency, multi-interval stalls, and exact interval boundaries.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
DataLayer's phoneMainActivitysends a demonstration/countDataItemevery 5 seconds while in the
RESUMEDlifecycle state. Although the existingloop attempts to subtract
sendCount(count)execution time from each sleepinterval, it anchors its schedule to
Instant.now()and resets that anchorafter
delay(...)returns. As a result, the schedule accumulates everycoroutine/main-thread wakeup overshoot (
O(N)phase drift) and can stall orfire early whenever the system wall clock changes.
This PR switches the
/counttrigger schedule to Android's monotonicSystemClock.elapsedRealtime()clock on a fixed 5-second grid, skipsalready-elapsed slots after multi-interval stalls so slow calls never trigger a
catch-up burst, clarifies in comments that periodic
DataClientticks arepurely for sample traffic generation, and adds unit tests covering the
scheduling invariants.
Problem
In
DataLayer/Application/src/main/java/com/example/android/wearable/datalayer/MainActivity.kt,the
RESUMEDloop previously scheduled/countupdates as follows:This has two timing bugs:
Cumulative wakeup-overshoot drift (
O(N)phase drift)Computing
Duration.between(Instant.now(), lastTriggerTime + countInterval)atthe top of the loop subtracts the time spent inside
sendCount(count)(
dataClient.putDataItem(...).await()). However, overwritinglastTriggerTime = Instant.now()afterdelay(...)returns anchors the nextdeadline to the actual wakeup instant rather than the scheduled deadline.
On Android,
delay(...)onDispatchers.Maindispatches via the main looperand wakes after at least the requested duration plus scheduling and frame/IPC
dispatch latency (
delta_i >= 0). Because each positive overshootdelta_iiswritten into
lastTriggerTime, every subsequent tick shifts later permanently(
t_k = t_0 + 1,000 ms + k * 5,000 ms + sum(delta_0..delta_k)):+delta_i)sendCountcompletiondelay(...)(old)01,000 ms1,008 ms(+8 ms)1,048 ms(40 msIPC)6,008 - 1,048 = 4,960 ms6,008 ms(+8 msdrift)16,000 ms6,020 ms(+12 ms)6,055 ms(35 msIPC)11,020 - 6,055 = 4,965 ms11,020 ms(+20 msdrift)k1,000 + 5,000k ms+sum(delta_i)Mutable wall-clock (
CLOCK_REALTIME) anchoringInstant.now()reads the system wall clock (CLOCK_REALTIME), which is notmonotonic and can jump forward or backward while the activity is open due to
automatic network time (NTP / carrier NITZ) corrections, timezone/clock updates,
or manual clock edits:
-Delta_t): If the system clock steps backwardby 10 minutes (
600,000 ms) betweenlastTriggerTime = Instant.now()and thenext
Duration.between(Instant.now(), lastTriggerTime + countInterval), thecomputed sleep duration becomes
~605,000 ms, stalling/countupdates forthe entire 10-minute backward adjustment.
+Delta_t): If the system clock jumps forward,Duration.between(...)becomes negative, causingdelay(...)to returnimmediately and re-anchoring
lastTriggerTimeto the new wall-clock time.(
Instant.now().epochSecondinsendPhoto()is intentionally retained becauseTIME_KEYrecords an event timestamp in theDataMappayload rather thanmeasuring an elapsed interval.)
Proposed Implementation
MainActivity.kt): ReplaceInstant.now()andjava.time.Durationinterval tracking withSystemClock.elapsedRealtime()(
CLOCK_BOOTTIME), preserving the 1-second initial delay(
INITIAL_COUNT_DELAY_MS = 1_000L) and 5-second period(
COUNT_INTERVAL_MS = 5_000L).(
nextCountTriggerRealtimeMs): AdvancenextTriggerRealtimeMsfrompreviousTriggerRealtimeMsin multiples ofCOUNT_INTERVAL_MSviainternal fun nextCountTriggerRealtimeMs(...), guardingdelay(delayMs)withif (delayMs > 0L).MainActivity.kt): Add a brief note above theloop clarifying that periodic
DataClientwrites whileRESUMEDexist onlyto generate visible demonstration traffic, whereas production Wear OS apps
should prefer event-driven state updates and self-ticking system surfaces
(such as
OngoingActivityStopwatchPart/TimerPartorTimeDifferenceComplicationText).MainActivityCountScheduleTest.kt,Application/build.gradle.kts): AddtestImplementation(libs.junit)to:Applicationand add fast JVM unit tests covering multi-iteration wakeupovershoots, sub-interval
sendCountlatency, multi-interval stalls, exactinterval boundaries, early wakeups, and invalid interval validation.
Edge Cases and Rationale
nextTriggerRealtimeMs += COUNT_INTERVAL_MSeliminates wakeup drift duringnormal operation, but leaves
nextTriggerRealtimeMsin the past if a slowputDataItem(...).await()call, debugger pause, or main-thread stall everexceeds
5,000 ms. For example, ifnextTriggerRealtimeMsis1,000 msandsendCount(0)stalls and completes at13,006 ms(ordelay()wakes at13,006 msafter a main-looper stall), a naive+5,000 msincrement wouldset the next deadline to
6,000 ms(< 13,006 ms) and emit back-to-backurgent
DataItemwrites until catching up. ComputingmissedIntervals = maxOf(0L, nowRealtimeMs - previousTriggerRealtimeMs) / intervalMsafter
sendCount(count)completes and returningpreviousTriggerRealtimeMs + (missedIntervals + 1L) * intervalMsskips theelapsed
6,000 msand11,000 msslots and schedules the next update at16,000 ms(2,994 mslater), preserving grid alignment with zero bursttraffic.
nowRealtimeMslands onan exact multiple of
COUNT_INTERVAL_MS(now = 6,000 msforprevious = 1,000 ms),missedIntervalsevaluates to1and returns11,000 ms(strictly in the future) rather than6,000 ms. If timer roundingever wakes slightly early (
now < previous),maxOf(0L, ...)clampsmissedIntervalsto0and advances by a single interval (6,000 ms).nextTriggerRealtimeMsisscoped inside
lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED)whilevar count = 0remains scoped toonCreate, pausing the activity cancels theloop cleanly and resuming starts a fresh 1-second initial delay without
resetting
countacross pause/resume cycles.Verification
From
DataLayer/::Applicationand:Wearable: